package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.dto.ShopUserInfoDTO;
import com.qianying.entity.*;
import com.qianying.mapper.ShopUserInfoMapper;
import com.qianying.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 门店用户信息Service实现类
 */
@Service
public class ShopUserInfoServiceImpl extends ServiceImpl<ShopUserInfoMapper, ShopUserInfo> implements ShopUserInfoService {

    @Autowired
    CustomerInfoService customerInfoService;
    @Autowired
    RegionService regionService;

    @Autowired
    ShopInfoService shopInfoService;

    @Autowired
    SysUserService sysUserService;

    @Override
    public CommonResult<?> saveShopUserInfo(ShopUserInfo shopUserInfo) {
        // 参数校验
        if (shopUserInfo.getUserId() == null) {
            return CommonResult.failed("用户ID不能为空");
        }
        shopUserInfo.setId(null);
        // 设置时间
        shopUserInfo.setCreateTime(LocalDateTime.now());
        shopUserInfo.setUpdateTime(LocalDateTime.now());

        // 执行保存
        boolean save = save(shopUserInfo);
        return save ? CommonResult.success("保存成功") : CommonResult.failed("保存失败");
    }

    @Override
    public CommonResult<?> updateShopUserInfo(ShopUserInfo shopUserInfo) {
        // 参数校验
        if (shopUserInfo.getId() == null) {
            return CommonResult.failed("ID不能为空");
        }

        // 设置更新时间
        shopUserInfo.setUpdateTime(LocalDateTime.now());

        // 执行更新
        boolean update = updateById(shopUserInfo);
        return update ? CommonResult.success("更新成功") : CommonResult.failed("更新失败");
    }

    @Override
    public CommonResult<?> removeShopUserInfoById(Long id) {
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }

        boolean remove = removeById(id);
        return remove ? CommonResult.success("删除成功") : CommonResult.failed("删除失败");
    }

    @Override
    public CommonResult<ShopUserInfo> getShopUserInfoById(Long id) {
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }

        ShopUserInfo shopUserInfo = getById(id);
        if (shopUserInfo != null) {
            changeIdToName(shopUserInfo);
            return CommonResult.success(shopUserInfo, "查询成功！");
        }
        return CommonResult.failed("未找到相关记录");
    }

    @Override
    public CommonResult<ShopUserInfo> getByUserId(Long userId) {
        if (userId == null) {
            return CommonResult.failed("用户ID不能为空");
        }

        LambdaQueryWrapper<ShopUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopUserInfo::getUserId, userId);

        ShopUserInfo shopUserInfo = getOne(queryWrapper);
        if (shopUserInfo != null) {
            changeIdToName(shopUserInfo);
            return CommonResult.success(shopUserInfo, "查询成功");
        }
        return CommonResult.failed("未找到相关记录");
    }

    @Override
    public CommonResult<List<ShopUserInfo>> getByCustomerId(Long customerId) {
        if (customerId == null) {
            return CommonResult.failed("客户ID不能为空");
        }

        LambdaQueryWrapper<ShopUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopUserInfo::getCustomerId, customerId)
                .orderByDesc(ShopUserInfo::getCreateTime);

        List<ShopUserInfo> list = list(queryWrapper);
        if (!list.isEmpty()) {
            for (ShopUserInfo shopUserInfo : list) {
                changeIdToName(shopUserInfo);
            }
        }
        return CommonResult.success(list);
    }

    @Override
    public CommonResult<List<ShopUserInfo>> getByShopId(Long shopId) {
        if (shopId == null) {
            return CommonResult.failed("门店ID不能为空");
        }

        LambdaQueryWrapper<ShopUserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopUserInfo::getShopId, shopId)
                .orderByDesc(ShopUserInfo::getCreateTime);

        List<ShopUserInfo> list = list(queryWrapper);
        if (!list.isEmpty()) {
            for (ShopUserInfo shopUserInfo : list) {
                changeIdToName(shopUserInfo);
            }
        }
        return CommonResult.success(list, "查询成功");
    }

    @Override
    public CommonResult<IPage<ShopUserInfoDTO>> getPageList(
            Integer pageNum,
            Integer pageSize,
            Long customerId,
            Long regionId,
            Long shopId,
            String department,
            String job,
            String realName) {

        // 初始化分页对象
        Page<ShopUserInfo> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<ShopUserInfo> queryWrapper = new LambdaQueryWrapper<>();

        // 客户ID筛选
        if (customerId != null) {
            queryWrapper.eq(ShopUserInfo::getCustomerId, customerId);
        }

        // 大区ID筛选
        if (regionId != null) {
            queryWrapper.eq(ShopUserInfo::getRegionId, regionId);
        }

        // 门店ID筛选
        if (shopId != null) {
            queryWrapper.eq(ShopUserInfo::getShopId, shopId);
        }

        // 部门筛选（模糊查询）
        if (StringUtils.hasText(department)) {
            queryWrapper.like(ShopUserInfo::getDepartment, department);
        }

        // 职务筛选（模糊查询）
        if (StringUtils.hasText(job)) {
            queryWrapper.like(ShopUserInfo::getJob, job);
        }

        // 姓名筛选（模糊查询）
        if (StringUtils.hasText(realName)) {
            queryWrapper.like(ShopUserInfo::getRealName, realName);
        }

        // 按姓名升序排序
        queryWrapper.orderByAsc(ShopUserInfo::getRealName);

        // 执行分页查询
        IPage<ShopUserInfo> pageResult = page(page, queryWrapper);

        List<ShopUserInfoDTO> shopUserInfoDTOList = new ArrayList<>();

        if (!pageResult.getRecords().isEmpty()) {
            for (ShopUserInfo record : pageResult.getRecords()) {
                changeIdToName(record);
                ShopUserInfoDTO shopUserInfoDTO = new ShopUserInfoDTO();
                shopUserInfoDTO.setShopUserInfo(record);
                ;

                SysUser sysUser = sysUserService.getById(record.getUserId());
                if (sysUser != null) {
                    shopUserInfoDTO.setDes(sysUser.getDes());
                    shopUserInfoDTO.setPhone(sysUser.getPhone());
                    shopUserInfoDTO.setIsEnable(sysUser.getEnabled());
                }
                shopUserInfoDTOList.add(shopUserInfoDTO);
            }
        }
        Page<ShopUserInfoDTO> resPage = new Page<>(pageResult.getCurrent(), pageResult.getPages());
        resPage.setRecords(shopUserInfoDTOList);

        return CommonResult.success(resPage);
    }

    private void changeIdToName(ShopUserInfo shopUserInfo) {
        if (shopUserInfo != null) {

            CustomerInfo customerInfo = customerInfoService.getById(shopUserInfo.getCustomerId());
            if (customerInfo != null) {
                shopUserInfo.setCustomerName(customerInfo.getCustomerName());
            }

            CommonResult<Region> rgionResult = regionService.getRegionById(shopUserInfo.getRegionId());
            if (rgionResult.isSuccess()) {
                shopUserInfo.setRegionName(rgionResult.getData().getRegionName());
            }

            CommonResult<ShopInfo> shopInfoResult = shopInfoService.getById(shopUserInfo.getShopId());
            if (shopInfoResult.isSuccess()) {
                shopUserInfo.setShopName(shopInfoResult.getData().getShopName());
            }
        }
    }

}
